package com.dm.webCrawler.framework.file;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import javax.annotation.PostConstruct;

import com.dm.webCrawler.common.utils.file.FileUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import com.dm.webCrawler.common.exception.CustomException;

/**
 * 本地文件系统实现类
 * @author Administrator
 *
 */
@Component
@ConfigurationProperties(prefix = "lb.file-system.local")
@ConditionalOnProperty(prefix = "lb.file-system",value = "type",havingValue = "LOCAL")
public class LocalFileSystem implements FileSystemInterface{
	
	private String basePath;
	
	private String httpPrefix;
	
	private File baseDir;
	
	
	@PostConstruct
	public void init() {
		baseDir=new File(basePath); 
		if(!baseDir.exists() || !baseDir.isDirectory()) {
			baseDir.mkdirs();
		}
	}
	
	public boolean saveFile(String savePath,InputStream localFileInput) {
		String absPath=baseDir.getAbsolutePath()+savePath;
		File saveFile= FileUtils.createFile(absPath);
		try {
			org.apache.commons.io.FileUtils.copyInputStreamToFile(localFileInput, saveFile);
			return true;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new CustomException("文件保存失败！");
		}
	}
	
	public File getBaseDir() {
		return baseDir;
	}

	public void setBaseDir(File baseDir) {
		this.baseDir = baseDir;
	}

	public String getBasePath() {
		return basePath;
	}

	public void setBasePath(String basePath) {
		this.basePath = basePath;
	}

	public String getHttpPrefix() {
		return httpPrefix;
	}

	public void setHttpPrefix(String httpPrefix) {
		this.httpPrefix = httpPrefix;
	}

	@Override
	public boolean hasFile(String filePath) {
		filePath=formatePath(filePath);
		File f=new File(formatePath(baseDir.getAbsolutePath())+filePath);
		return f.exists() && f.isFile();
	}
	
	private String formatePath(String path) {
		path=path.replace("\\", "/");
		if(!path.startsWith("/")) {
			path="/"+path;
		}
		return path;
	}

	@Override
	public boolean deleteFile(String filePath) {
		filePath=formatePath(filePath);
		File f=new File(formatePath(baseDir.getAbsolutePath())+filePath);
		return f.delete();
	}

	@Override
	public String httpPrefix() {
		// TODO Auto-generated method stub
		return httpPrefix;
	}
	
}
